/*===============================
	Define project status enum
*/
ProjectStatusEnum = function() {
	this.ConceptDraft = 3,
	this.ConceptPendingApproval = 4,
	this.ConceptApproved = 5,
	this.ProjectDraft = 6,
	this.ProjectPendingApproval = 7,
	this.ProjectApproved = 8
}
var ProjectStatus = new ProjectStatusEnum();
/* End of project status definition */

var _programmeID = null;
if (crmForm.all.ca_programmeid.DataValue != null && crmForm.all.ca_programmeid.DataValue[0] != null)
{
  _programmeID = crmForm.all.ca_programmeid.DataValue[0].id;
}

FormOverviewTabHandler();

function FormOverviewTabHandler()
{   
    HandleProgrammeChange();
    HandleProgrammeObjectiveChange();
    HadleCSOChange();
    HandleSPF();
    
    crmForm.all.ca_programmeid.attachEvent("onchange",HandleProgrammeChange);
    crmForm.all.ca_programmeobjectiveid.attachEvent("onchange",HandleProgrammeObjectiveChange);
    crmForm.all.ca_csoid.attachEvent("onchange",HadleCSOChange);
    crmForm.all.ca_projecttype1id.attachEvent("onchange",SetProjectTypeFetch);
    crmForm.all.ca_projecttype2id.attachEvent("onchange",SetProjectTypeFetch);
    crmForm.all.ca_projecttype3id.attachEvent("onchange", SetProjectTypeFetch);

    crmForm.all.ca_primarylocationid.attachEvent("onchange", SetLocationFetch);
    crmForm.all.ca_location2id.attachEvent("onchange", SetLocationFetch);
    crmForm.all.ca_location3id.attachEvent("onchange", SetLocationFetch);
    
    crmForm.all.ca_isspf.attachEvent("onchange",HandleSPF);
    
    function HandleSPF()
    {
        var fundRaisinf = crmForm.all.ca_issutableforfundraising;
        if (crmForm.all.ca_isspf!=null && crmForm.all.ca_isspf.DataValue!=null && crmForm.all.ca_isspf.DataValue==true)
        {
            fundRaisinf.DataValue = false;
            fundRaisinf.Disabled = true;
            fundRaisinf.ForceSubmit = true;
        }
        else
        {
            fundRaisinf.Disabled = false;
        }
    }
    
    
    function HandleProgrammeChange()
    {
        if (crmForm.all.ca_programmeid.DataValue == null || crmForm.all.ca_programmeid.DataValue[0] == null)
        {
            crmForm.all.ca_projectmanagerid.DataValue = null;
            crmForm.all.ca_projectmanagerid.Disabled = true;
        }
        else
        {
            crmForm.all.ca_projectmanagerid.Disabled = false;
            if (crmForm.all.ca_programmeid.DataValue[0].id != _programmeID)
            {
                _programmeID = crmForm.all.ca_programmeid.DataValue[0].id;
                crmForm.all.ca_projectmanagerid.DataValue = null;
                SetProjectProposerFilteredLookup();
            }
        }

        var poField = crmForm.all.ca_programmeobjectiveid;
        var locPimField = crmForm.all.ca_primarylocationid;
        var loc2Field = crmForm.all.ca_location2id;
        var loc3Field = crmForm.all.ca_location3id;
            
        var progField = crmForm.all.ca_programmeid;
        if (progField.IsDirty)
        {
            poField.DataValue = null;
            locPimField.DataValue = null;
            loc2Field.DataValue = null;
            loc3Field.DataValue = null;
        }
        
        if (progField.DataValue == null || progField.DataValue[0]==null)
        {
            poField.DataValue = null;
            poField.Disabled = true;
            poField.ForceSubmit = true;

            locPimField.DataValue = null;
            locPimField.Disabled = true;
            locPimField.ForceSubmit = true;

            loc2Field.DataValue = null;
            loc2Field.Disabled = true;
            loc2Field.ForceSubmit = true;

            loc3Field.DataValue = null;
            loc3Field.Disabled = true;
            loc3Field.ForceSubmit = true;
        }
        else
        {
            poField.Disabled = false;
            locPimField.Disabled = false;
            loc2Field.Disabled = false;
            loc3Field.Disabled = false;
            
            //Filtered PO
            var fetchXML = '<fetch mapping="logical"><entity name="ca_programmeobjective"><filter><condition attribute="ca_programmeid" operator="eq" value="' + progField.DataValue[0].id + '" /></filter></entity></fetch>';
            // Ensure that search box is not visible in a lookup dialog
            poField.lookupbrowse = 1; 
            // Pass fetch xml through search value parameter
            poField.AddParam("search", fetchXML);

            
            
            //Filtered Locations
            //Getting Programme Location
            var service = new Ascentium_CrmService();
            var asCols = ["ca_locationid"];
            var beRetrievedProgramme = service.Retrieve("ca_programme", progField.DataValue[0].id, asCols);
            if (beRetrievedProgramme != null && beRetrievedProgramme.attributes["ca_locationid"] != null)
            {
                _programmeLocationID = beRetrievedProgramme.attributes["ca_locationid"].value;
                SetLocationFetch();
            }
        }
        
        HandleProgrammeObjectiveChange();
    }

    var _programmeLocationID = null;

    function SetLocationFetch()
    {

        var locPimField = crmForm.all.ca_primarylocationid;
        var loc2Field = crmForm.all.ca_location2id;
        var loc3Field = crmForm.all.ca_location3id;


        if (_programmeLocationID != null)
        {
            // Retrieve all 2-nd level locations for current primary location
            var oService = new Ascentium_CrmService();

            var sLocationsOfSecondLevelFetchXml = '<fetch mapping="logical"><entity name="ca_location"><attribute name="ca_locationid" /><filter><condition attribute="ca_regionid" operator="eq" value="' + _programmeLocationID + '" /></filter></entity></fetch>';

            var aoFetchLocationsOfSecondLevelResults = oService.Fetch(sLocationsOfSecondLevelFetchXml); 
            var iNumOfLocations = aoFetchLocationsOfSecondLevelResults.length;
            var sLocationOfSecondLevelFilter = "";

            if (iNumOfLocations > 0)
            {
              for (i = 0; i< iNumOfLocations; i++)
              {
                sLocationOfSecondLevelFilter += '<condition attribute="ca_regionid" operator="eq" value="' + aoFetchLocationsOfSecondLevelResults[i].attributes["ca_locationid"].value + '" />';
              }
            }

            SetPrimaryLocation(_programmeLocationID);

            var exlCondition = "";
            if (locPimField.DataValue != null)
                exlCondition = exlCondition + '<filter><condition attribute="ca_locationid" operator="ne" value="' + locPimField.DataValue[0].id + '" /></filter>';

            if (loc2Field.DataValue != null)
                exlCondition = exlCondition + '<filter><condition attribute="ca_locationid" operator="ne" value="' + loc2Field.DataValue[0].id +'" /></filter>';

            if (loc3Field.DataValue != null)
                exlCondition = exlCondition + '<filter><condition attribute="ca_locationid" operator="ne" value="' + loc3Field.DataValue[0].id + '" /></filter>';

            var fetchXML = '<fetch mapping="logical"><entity name="ca_location"><filter><filter type="or"><condition attribute="ca_locationid" operator="eq" value="' + _programmeLocationID + '" /><condition attribute="ca_regionid" operator="eq" value="' + _programmeLocationID + '" />' + sLocationOfSecondLevelFilter + '</filter>' + exlCondition + ' </filter></entity></fetch>';

            // Ensure that search box is not visible in a lookup dialog
            locPimField.lookupbrowse = 1;
            loc2Field.lookupbrowse = 1;
            loc3Field.lookupbrowse = 1;

            // Pass fetch xml through search value parameter
            locPimField.AddParam("search", fetchXML);
            loc2Field.AddParam("search", fetchXML);
            loc3Field.AddParam("search", fetchXML);

        }
    }


    //=====================================================
    // Bug 1763
    //=====================================================
    function SetPrimaryLocation(sPrimaryLocationId)
    {
      if (typeof(sPrimaryLocationId) != "undefined" && sPrimaryLocationId != null && sPrimaryLocationId != "")
      {
        var service = new Ascentium_CrmService();
        var asCols = ["ca_name", "ca_regionid", "ca_locationid"];
        var beRetrievedLocation = service.Retrieve("ca_location", sPrimaryLocationId, asCols);

        if (beRetrievedLocation != null)
        {
          var sLocationName = beRetrievedLocation.attributes["ca_name"].value;

          var aPrimaryLocationLookupData = new Array();
          var aPrimaryLocationLookupItem = new Object();
          aPrimaryLocationLookupItem.id = sPrimaryLocationId;
          aPrimaryLocationLookupItem.typename = "ca_location";
          aPrimaryLocationLookupItem.name = sLocationName;
          aPrimaryLocationLookupData[0] = aPrimaryLocationLookupItem;
          crmForm.all.ca_primarylocationid.DataValue = aPrimaryLocationLookupData;
        }
      }
    }  
    //=====================================================

    function HandleProgrammeObjectiveChange()
    {
        var csoField = crmForm.all.ca_csoid;
        var conditions ="";
        var enableTypes = false;
            
        var poField = crmForm.all.ca_programmeobjectiveid;
        if (poField.IsDirty)
        {
            csoField.DataValue = null;
        }
        
        
        if (poField.DataValue == null || poField.DataValue[0]==null)
        {
            csoField.DataValue = null;
            csoField.Disabled = true;
            csoField.ForceSubmit = true;
            SetMainStreamFlag();
        }
        else
        {
            //Setting Mainstream Flag
            var pId = poField.DataValue[0].id;
	        //Create the Ascentium_CrmService object
	        var service = new Ascentium_CrmService();
	        //Retrieve an entity asynchronously by passing a callback function to the Retrieve method
	        var asCols = ["ca_programmeobjectivetype", "ca_csopriority1id", "ca_csopriority2id", "ca_csopriority3id"];
	        var result = service.Retrieve("ca_programmeobjective", pId, asCols);
	        SetMainStreamFlag(result);
            /////
        
            csoField.Disabled = false;
            
            if (result!=null && result.attributes["ca_csopriority1id"]!=null)
            {
                conditions = conditions + '<condition attribute="ca_corporatestrategyobjectiveid" operator="eq" value="'+result.attributes["ca_csopriority1id"].value+'" />'
            }
            if (result!=null && result.attributes["ca_csopriority2id"]!=null)
            {
                conditions = conditions + '<condition attribute="ca_corporatestrategyobjectiveid" operator="eq" value="'+result.attributes["ca_csopriority2id"].value+'" />'
            }
            if (result!=null && result.attributes["ca_csopriority3id"]!=null)
            {
                conditions = conditions + '<condition attribute="ca_corporatestrategyobjectiveid" operator="eq" value="'+result.attributes["ca_csopriority3id"].value+'" />'
            }
            
            if (conditions!="")
            {
                enableTypes = true;
                var fetchXML = '<fetch mapping="logical" distinct="true"><entity name="ca_corporatestrategyobjective"><filter type="or">' + conditions + '</filter></entity></fetch>';
                
                // Ensure that search box is not visible in a lookup dialog
                csoField.lookupbrowse = 1; 
                
                // Pass fetch xml through search value parameter 
                csoField.AddParam("search", fetchXML);
            }
        }
        
        HadleCSOChange(enableTypes);
    }

    function SetMainStreamFlag(beResult)
    {
        var isMainStream = false;
        if (beResult!=null && beResult.attributes["ca_programmeobjectivetype"]!=null)
        {
            isMainStream = beResult.attributes["ca_programmeobjectivetype"].value ==2;
        }
        crmForm.all.ca_mainstreamingobjective.DataValue = isMainStream;
        crmForm.all.ca_mainstreamingobjective.ForceSubmit = true;
    }
    
    function HadleCSOChange(enableTypes)
    {
        
        var ptojectType1Field = crmForm.all.ca_projecttype1id;
        var ptojectType2Field = crmForm.all.ca_projecttype2id;
        var ptojectType3Field = crmForm.all.ca_projecttype3id;
            
        var csoField = crmForm.all.ca_csoid;
        
        if (csoField.IsDirty)
        {
            ptojectType1Field.DataValue = null;
            ptojectType2Field.DataValue = null;
            ptojectType3Field.DataValue = null;
            
            ptojectType1Field.ForceSubmit = true;
            ptojectType2Field.ForceSubmit = true;
            ptojectType3Field.ForceSubmit = true;
        }
        
        
        if (csoField.DataValue == null || csoField.DataValue[0]==null || (enableTypes!=null && enableTypes==false) )
        {
            _csoObjectiveArea = null;
            
            ptojectType1Field.DataValue = null;
            ptojectType2Field.DataValue = null;
            ptojectType3Field.DataValue = null;
            
            ptojectType1Field.Disabled = true;
            ptojectType2Field.Disabled = true;
            ptojectType3Field.Disabled = true;
            
            ptojectType1Field.ForceSubmit = true;
            ptojectType2Field.ForceSubmit = true;
            ptojectType3Field.ForceSubmit = true;
        }
        else
        {
            ptojectType1Field.Disabled = false;
            ptojectType2Field.Disabled = false;
            ptojectType3Field.Disabled = false;
            var service = new Ascentium_CrmService();
            //Retrieve an entity asynchronously by passing a callback function to the Retrieve method
	        var asCols = ["ca_objectivearea"];
	        var results = service.Retrieve("ca_corporatestrategyobjective", csoField.DataValue[0].id, asCols);
	        if (results!=null && results.attributes["ca_objectivearea"]!=null)
	        {
	            
	            _csoObjectiveArea = results.attributes["ca_objectivearea"].name.toLowerCase();
	        }
            /////


            SetProjectTypeFetch();
        }
    }
    var _csoObjectiveArea = null;
    function SetProjectTypeFetch()
    {
        var ptojectType1Field = crmForm.all.ca_projecttype1id;
        var ptojectType2Field = crmForm.all.ca_projecttype2id;
        var ptojectType3Field = crmForm.all.ca_projecttype3id;
            
        var csoField = crmForm.all.ca_csoid;
         if (_csoObjectiveArea!=null)
        {
                        
            var extaCondition = "";
            if (ptojectType1Field.DataValue!=null)
                extaCondition = extaCondition  + '<condition attribute="ca_csocapprojecttypeid" operator="ne" value="' + ptojectType1Field.DataValue[0].id + '" />';
                
            if (ptojectType2Field.DataValue!=null)
                extaCondition = extaCondition  + '<condition attribute="ca_csocapprojecttypeid" operator="ne" value="' + ptojectType2Field.DataValue[0].id + '" />';
                
            if (ptojectType3Field.DataValue!=null)
                extaCondition = extaCondition  + '<condition attribute="ca_csocapprojecttypeid" operator="ne" value="' + ptojectType3Field.DataValue[0].id + '" />';
            
            
            var fetchXML = '<fetch mapping="logical" distinct="true"><entity name="ca_csocapprojecttype"><filter><condition attribute="ca_' + _csoObjectiveArea + '" operator="eq" value="1" />' + extaCondition + '</filter></entity></fetch>';
            
            // Ensure that search box is not visible in a lookup dialog
            ptojectType1Field.lookupbrowse = 1; 
            ptojectType2Field.lookupbrowse = 1; 
            ptojectType3Field.lookupbrowse = 1; 
            
            // Pass fetch xml through search value parameter 
            ptojectType1Field.AddParam("search", fetchXML); 
            ptojectType2Field.AddParam("search", fetchXML); 
            ptojectType3Field.AddParam("search", fetchXML);
        }
    }
}


LoadViewInFrame("IFRAME_Grant", "ca_ca_project_ca_grant", "ca_ca_project_ca_grant", GrantsGridLoaded, null, null, null,  "ca_projectid", "ca_project");
function RegisterGrantsGridEvents()
{
        var topGrid= crmForm['ca_ca_project_ca_grant'];
        var totalGrantsField = crmForm.all.ca_grants_tc;
        var summofGrants = 0;
        topGrid.onrefresh = RegisterGrantsGridEvents;

        var oGrid = topGrid.InnerGrid;
        oGrid.onselectionchange=OnGrantSelectedChanged;
        for(var row = 0; row < oGrid.rows.length; row++)
        {
              if(oGrid.rows[row].cells[5]!=null && oGrid.rows[row].cells[5].innerText != "")
                summofGrants = summofGrants + LocStringToFloat(oGrid.rows[row].cells[5].innerText);
        }
        totalGrantsField.value = AddFormatting(summofGrants,2,false);

        if (oGrid.SelectedRecords.length>0)
        {
            var gid = oGrid.rows[0].oid;

            LoadViewInFrame("IFRAME_Transfer","ca_ca_grant_ca_transfer","ca_ca_grant_ca_transfer", HideAddExisitngTransfer, gid, oGrid.oname, null, "ca_grantid", "ca_grant");
        }
}
var _selectedGrantID ="";

function GrantsGridLoaded()
{
    
    if (event.srcElement.readyState == "complete" ||  event.srcElement.readyState == "loaded" )
    {
        RegisterGrantsGridEvents();
    }

}

function OnGrantSelectedChanged(event)
{
    var oGrid = crmForm['ca_ca_project_ca_grant'].InnerGrid;
    if (oGrid.SelectedRecords.length>0)
    {
        var newSelctedID = oGrid.SelectedRecords[0][0];
        if (newSelctedID != _selectedGrantID)
        {
            _selectedGrantID = newSelctedID;
            LoadViewInFrame("IFRAME_Transfer","ca_ca_grant_ca_transfer","ca_ca_grant_ca_transfer", HideAddExisitngTransfer, newSelctedID, oGrid.oname, null,  "ca_grantid", "ca_grant");
        }
    }
}

function HideAddExisitngTransfer()
{
    HideButtonOnGrid("IFRAME_Transfer",["Add existing Transfer to this record"]);
}


/*==============================
	Validate that all fields required fields are populated befor submitting for approval 
	The Years in Project field will display current year/number of project years dates specified in the Start and End Dates
	Task: 1354
*/
var startDateField = new CrmField("ca_projectstartdate");
var endDateField = new CrmField("ca_projectenddate");
CalculateYearsInProject = function()
{
	if (!(startDateField.Field.DataValue && endDateField.Field.DataValue)) 
		return; // Start date or end date is empty - nothing to calculate
	
	var yearsInProject = new CrmField("ca_yearsinaproject");
	
	var startDateTicks = Date.parse(startDateField.Field.DataValue);
	var endDateTicks = Date.parse(endDateField.Field.DataValue);
	if (startDateTicks > endDateTicks)
	{
		alert("Start date is later than end date!");
		yearsInProject.Field.DataValue = 0;
		return;
	}
	
	var startDate = new Date();
	startDate.setTime(startDateTicks);
	var endDate = new Date();
	endDate.setTime(endDateTicks);
	
	yearsInProject.Field.DataValue = endDate.getFullYear() - startDate.getFullYear();
}
startDateField.OnChange(CalculateYearsInProject);
endDateField.OnChange(CalculateYearsInProject);
CalculateYearsInProject();

window.SubmitProject = function()
{
	// Get current project status first
	var statusField = new CrmField("ca_status");
	var currentStatus = statusField.Field.DataValue;

	// Validate required fields
	if (currentStatus != ProjectStatus.ConceptDraft
		&& currentStatus != ProjectStatus.ConceptPendingApproval)
	{
		// Require grants
		if (!HasGrants())
		{
			alert("Add a grant before submit for approval");
			return;
		}

		// Require Transfers
		if (!HasTransfers())
		{
			alert("Add a Transfer before submit for approval");
			return;
		}
	}

	var recomendedFieldIds = ["ca_programmeid", "ca_partnerid", "ca_programmeobjectiveid", "ca_projectstartdate",
		"ca_projectenddate", "ca_disasteraffectedtargetgroup"];

	// Require all recommended fields 	
	for (var i = 0; i < recomendedFieldIds.length; i++)
	{
		var field = new CrmField(recomendedFieldIds[i]);
		field.Required();
	}

	// Change status of the entity to pending
	if (currentStatus == ProjectStatus.ConceptDraft)
		statusField.Field.DataValue = ProjectStatus.ConceptPendingApproval;
	else if (currentStatus == ProjectStatus.ProjectDraft)
		statusField.Field.DataValue = ProjectStatus.ProjectPendingApproval;
	
	var saveResult = crmForm.Save();
//	if (saveResult == false)
//	{
//		// All required fields are not required any more
//		for (var i = 0; i < recomendedFieldIds.length; i++)
//		{
//			var field = new CrmField(recomendedFieldIds[i]);
//			field.NotRequired();
//		}
//		return;
//	}

	
	
//	crmForm.Save();
}

HasGrants = function()
{
	if (crmForm.FormType != UPDATE_FORM)
		return false;
	
	//Creating instance of the CrmService helper class
	var service = new Ascentium_CrmService();
	
	//Retrieving number of the grants already created by the user
	var fetchXml = '<fetch mapping="logical"><entity name="ca_grant"><attribute name="ca_projectid" />' + 
		'<filter><condition attribute="ca_projectid" operator="eq" value="'+ crmForm.ObjectId +'" />' +
		'</filter></entity></fetch>'; 
	var results = service.Fetch(fetchXml); 
	return results.length > 0;
}

HasTransfers = function()
{
	if (crmForm.FormType != UPDATE_FORM)
		return false;
	
	//Creating instance of the CrmService helper class
	var service = new Ascentium_CrmService();
	
	//Retrieving number of transfers already created by the user
	var fetchXml = '<fetch mapping="logical"><entity name="ca_transfer"><attribute name="ca_projectid" />' + 
		'<filter><condition attribute="ca_projectid" operator="eq" value="'+ crmForm.ObjectId +'" />' +
		'</filter></entity></fetch>';
	var results = service.Fetch(fetchXml); 
	return results.length > 0;
}
HideShowSaveAsConceptOrProjectButtons();
function HideShowSaveAsConceptOrProjectButtons() {
	var statusField = new CrmField("ca_status");
	var currentStatus = statusField.Field.DataValue;

	if (currentStatus != ProjectStatus.ConceptApproved || currentStatus != ProjectStatus.ConceptDraft) {
		ShowHideEntityIsvCustomMenuItem("Save Project Concept as Project", false);
	}
	if (currentStatus != ProjectStatus.ProjectDraft) {
		ShowHideEntityIsvCustomMenuItem("Save Project as Concept", false);
	}

	if (currentStatus != ProjectStatus.ProjectDraft && currentStatus != ProjectStatus.ConceptDraft) {
		ShowHideEntityIsvCustomMenuItem("Project Actions", false);
	}

}

window.SaveAsConcept = function() 
{
	crmForm.all.ca_status.DataValue = ProjectStatus.ConceptDraft;
	crmForm.Save();
}

window.SaveConceptAsProject = function()
{
	crmForm.all.ca_status.DataValue = ProjectStatus.ProjectDraft;
	crmForm.Save();
}
/* End task */
/*=============================================================
	Task: 1370
	Show 'Monitoring' and 'Closure Activities' tabs after approval
*/
HideShowMonitoringAndClosureActivitiesTabs = function()
{
	var status = parseInt((new CrmField('ca_status')).Field.DataValue);
	if (status != ProjectStatus.ProjectApproved && status != ProjectStatus.ConceptApproved)
	{
		HideTab('Closure Activities');
		HideTab('Monitoring');
	}
}
HideShowMonitoringAndClosureActivitiesTabs();

LoadViewInFrame("IFRAME_Documentation", "ca_project_ca_documentation", "ca_project_ca_documentation");
/* End of Task: 1370 */

/*========================================
	Task 1521: When user selectes Suitable for offsetting flag new field "Offsetting Rating" must become visible 
*/
var suitable = new CrmField("ca_suitableforoffsetting");
SetOffsettingRating = function()
{
	var offsettingRating = new CrmField("ca_offsettingrating");
	if (suitable.Field.DataValue)
		offsettingRating.ShowCell();
	else offsettingRating.HideCell();
}
SetOffsettingRating();
suitable.OnChange(SetOffsettingRating);
/* End task 1521 */
/*=======================================
	The Seconder filtered lookup will meet the conditions below: 
		Risk Rating = Super High: Proposer's Head of Division 
		Risk Rating = High: Staff Member with Level 1 Authority 
		Risk Rating = Medium: Staff Member with Level 2 Authority 
		Risk Rating = Low: Staff Member with Level 3 Authority 
	Task: 1371
*/
ChoseSeconder = function()
{
  var seconderField = new CrmField("ca_projectseconderid");
  if (!crmForm.ObjectId)
  {
    seconderField.Disable();
    return;
  }

  var sFetchXml = "";
  
  // Super High Risk
  if (crmForm.all.ca_projectriskraiting.DataValue == 4)
  {
    sFetchXml ='<fetch mapping="logical"><entity name="systemuser"><attribute name="systemuserid" /><link-entity name="ca_division" from="owninguser" to="systemuserid"><link-entity name="ca_unit" from="ca_divisionid" to="ca_divisionid"><link-entity name="ca_programme" from="ca_unitid" to="ca_unitid"><link-entity name="ca_project" from="ca_programmeid" to="ca_programmeid"><filter><condition attribute="ca_projectid" operator="eq" value="' + crmForm.ObjectId + '" /></filter></link-entity></link-entity></link-entity></link-entity></entity></fetch>';
  }

  // High Risk
  if (crmForm.all.ca_projectriskraiting.DataValue == 3)
  {
    sFetchXml ='<fetch mapping="logical"><entity name="systemuser"><attribute name="systemuserid" /><link-entity name="systemuserroles" from="systemuserid" to="systemuserid"><link-entity name="role" from="roleid" to="roleid"><filter><condition attribute="name" operator="eq" value="PromiseLevel1Authority" /></filter></link-entity></link-entity></entity></fetch>';
  }

  // Medium Risk
  if (crmForm.all.ca_projectriskraiting.DataValue == 2)
  {
    sFetchXml ='<fetch mapping="logical"><entity name="systemuser"><attribute name="systemuserid" /><link-entity name="systemuserroles" from="systemuserid" to="systemuserid"><link-entity name="role" from="roleid" to="roleid"><filter><condition attribute="name" operator="eq" value="PromiseLevel2Authority" /></filter></link-entity></link-entity></entity></fetch>';
  }

  // Low Risk
  if (crmForm.all.ca_projectriskraiting.DataValue == 1)
  {
    sFetchXml ='<fetch mapping="logical"><entity name="systemuser"><attribute name="systemuserid" /><link-entity name="systemuserroles" from="systemuserid" to="systemuserid"><link-entity name="role" from="roleid" to="roleid"><filter><condition attribute="name" operator="eq" value="PromiseLevel3Authority" /></filter></link-entity></link-entity></entity></fetch>';
  }

  if (sFetchXml != "")
  {
    seconderField.Field.lookupbrowse = 1;
    seconderField.Field.AddParam("search", sFetchXml);
  }
}

ChoseSeconder();

/* End Task: 1371 */

/*  */

/**/


//==========================================================================================
// Iteration 3 - Quality And Risk 
//==========================================================================================

FormDesignForIteration3();
LoadQualityAndRiskForm();
LoadMonitoringAndAssessmentForm();

function LoadQualityAndRiskForm()
{
  if (crmForm.FormType == CREATE_FORM)
  {
    crmForm.all["IFRAME_QualityAndRisk"].src = CRM_URL + "/ISV/Ascentium/CustomPages/IframeSplashPage.aspx";
  }
  //else if (crmForm.FormType == UPDATE_FORM)
  else
  {
    var sQualityAndRiskId = GetLastQualityAndRiskId();
    if (sQualityAndRiskId != null)  
    {
      LoadEntityTabInIFrame("IFRAME_QualityAndRisk", "ca_qualityandrisk", sQualityAndRiskId, 0, QualityAndRiskFrameLoaded, "projectid=" + crmForm.ObjectId);

      if (IsOnline())
      {
        var service = new Ascentium_CrmService();
        
        var beQualityAndRiskToUpdate = new BusinessEntity("ca_qualityandrisk");
        beQualityAndRiskToUpdate.attributes["ca_qualityandriskid"] = sQualityAndRiskId;
        beQualityAndRiskToUpdate.attributes["statuscode"] = 3;
        service.Update(beQualityAndRiskToUpdate);

        if (crmForm.all.ca_projectriskraiting.DataValue == null)
        {
          window.FirstProjectRiskRating = 0;
        }
        else
        {
          window.FirstProjectRiskRating = parseInt(crmForm.all.ca_projectriskraiting.DataValue);
        }

        setTimeout(CheckProjectRiskRating, 5000);
      }
    }
    else
    {
      LoadEntityTabInIFrame("IFRAME_QualityAndRisk", "ca_qualityandrisk", "", 0);
    }
  }

  function CheckProjectRiskRating() 
  {
    var sProjectGuid = crmForm.ObjectId;
    var asColums = ["ca_projectriskraiting"];
    var beRetrievedQualityAndRisk = service.Retrieve("ca_project", sProjectGuid, asColums);
    
    if (typeof(beRetrievedQualityAndRisk.attributes["ca_projectriskraiting"]) == "undefined" || beRetrievedQualityAndRisk.attributes["ca_projectriskraiting"] == null)
    {
      window.LastProjectRiskRating = 0;
    }
    else
    {
      window.LastProjectRiskRating = parseInt(beRetrievedQualityAndRisk.attributes["ca_projectriskraiting"].value);
    }

    if (window.FirstProjectRiskRating != window.LastProjectRiskRating)
    {      
      ShowNotice("Project Risk Rating has been changed!");
      crmForm.all.ca_projectriskraiting.DataValue = window.LastProjectRiskRating;
      crmForm.all.ca_projectseconderid.DataValue = null;
      EnableDisableSeconderField();
    }

    //alert("window.FirstProjectRiskRating = " + window.FirstProjectRiskRating + " | window.LastProjectRiskRating = " + window.LastProjectRiskRating + " | Equals = " + (window.FirstProjectRiskRating == window.LastProjectRiskRating));

    setTimeout(CheckProjectRiskRating, 5000);
  }
}

function LoadMonitoringAndAssessmentForm()
{
  if (crmForm.FormType == CREATE_FORM)
  {
    crmForm.all["IFRAME_MonitoringAndAssessment"].src = CRM_URL + "/ISV/Ascentium/CustomPages/IframeSplashPage.aspx";
  }
  //else if (crmForm.FormType == UPDATE_FORM)
  else
  {
    var sMonitoringAndAssessmentId = GetLastMonitoringAndAssessment();
    if (sMonitoringAndAssessmentId != null)  
    {
      LoadEntityTabInIFrame("IFRAME_MonitoringAndAssessment", "ca_monitoringassessment", sMonitoringAndAssessmentId, 0, null, "projectid=" + crmForm.ObjectId);
    }
    else
    {
      LoadEntityTabInIFrame("IFRAME_MonitoringAndAssessment", "ca_monitoringassessment", "", 0);
    }
  }
}

function GetLastQualityAndRiskId()
{
  var sResult = null;
  if (crmForm.FormType == UPDATE_FORM)
  {
    var oService = new Ascentium_CrmService();	 
    var sFetchXml = '<fetch mapping="logical" count="1"><entity name="ca_qualityandrisk"><attribute name="ca_qualityandriskid" /><order attribute="createdon" descending="true" /><filter><condition attribute="ca_projectid" operator="eq" value="' + crmForm.ObjectId + '" /></filter></entity></fetch>'; 
    var aoFetchResults = oService.Fetch(sFetchXml); 

    var numOfRecords = aoFetchResults.length;
    if (numOfRecords > 0)
    {
      sResult =  aoFetchResults[0].attributes["ca_qualityandriskid"].value;
    }
    else
    {
      sResult = null;
    }
  }
  return sResult;
}

function GetLastMonitoringAndAssessment()
{
  var sResult = null;
  if (crmForm.FormType == UPDATE_FORM)
  {
    var oService = new Ascentium_CrmService();	 

    var sFetchXml = '<fetch mapping="logical" count="1"><entity name="ca_monitoringassessment"><attribute name="ca_monitoringassessmentid" /><order attribute="createdon" descending="true" /><filter><condition attribute="ca_projectid" operator="eq" value="' + crmForm.ObjectId + '" /></filter></entity></fetch>';

    var aoFetchResults = oService.Fetch(sFetchXml); 

    var numOfRecords = aoFetchResults.length;
    if (numOfRecords > 0)
    {
      sResult =  aoFetchResults[0].attributes["ca_monitoringassessmentid"].value;
    }
    else
    {
      sResult = null;
    }
  }
  return sResult;
}

function FormDesignForIteration3()
{
  EnableDisableSeconderField();
  var bIsAbleToseeCriticalIssues = IsAbleToseeCriticalIssues();

  var oProjectRiskField = new CrmField("ca_projectriskraiting");
  oProjectRiskField.OnChange(EnableDisableSeconderField);

  if (crmForm.FormType == CREATE_FORM)
  {
    crmForm.all["IFRAME_CriticalIssues"].src = CRM_URL + "/ISV/Ascentium/CustomPages/IframeSplashPage.aspx";
  }
  else
  {
    LoadViewInFrame("IFRAME_CriticalIssues", "ca_project_ca_criticalissue", "ca_project_ca_criticalissue", CriticalIssuesGridLoaded);
  }

  if (!bIsAbleToseeCriticalIssues)
  {
    HideTab("Critical Issues");
  }

  HideField("ca_lastqrrecordid");
  HideField("ca_lastmonitoringassessmentid");
  HideField("ownerid");
  HideField("ca_helperfield");
}

function EnableDisableSeconderField()
{
  crmForm.all.ca_projectseconderid.Disabled = crmForm.all.ca_projectriskraiting.DataValue == null;
  ChoseSeconder();
}

function CriticalIssuesGridLoaded()
{
}

function QualityAndRiskFrameLoaded()
{
/*
  if (crmForm.FormType == UPDATE_FORM && typeof(document.frames("IFRAME_QualityAndRisk").crmForm) != "undefined" && document.frames("IFRAME_QualityAndRisk").crmForm != null)
  {
    var sLastQAndRId = GetLastQualityAndRiskId();
    var iObjectTypeCode = document.frames("IFRAME_QualityAndRisk").crmForm.ObjectTypeCode;
    if (sLastQAndRId != null && sLastQAndRId != "") LoadViewInFrame("IFRAME_CriticalIssues", "ca_qualityandrisk_ca_criticalissue", "ca_qualityandrisk_ca_criticalissue", CriticalIssuesGridLoaded, sLastQAndRId, iObjectTypeCode);
  }
*/
}

function IsAbleToseeCriticalIssues()
{
  var bUserIsInProjectTeam = IsUserInProjectTeam();
  if (ROLE_PROMISE_SUPER_USER || ROLE_PROMISE_INTERNAL_AUDIT || ROLE_PROMISE_SYSTEM_ADMINISTRATOR || ROLE_PROMISE_ID_SMT || ROLE_SYSTEM_ADMINISTRATOR || ROLE_PROMISE_SENSITIVE_PARTNER_CRITICAL_ISSUES_COMMON || bUserIsInProjectTeam)
  {
    return true;
  }
  return false;
}

function IsUserInProjectTeam()
{
  if (crmForm.FormType == UPDATE_FORM)
  {
    var oService = new Ascentium_CrmService();	 

    var sFetchXml = '<fetch mapping="logical"><entity name="systemuser"><attribute name="systemuserid" /><filter><condition attribute="systemuserid" operator="eq" value="{' + USER_ID + '}" /></filter><link-entity name="teammembership" from="systemuserid" to="systemuserid"><link-entity name="team" from="teamid" to="teamid"><link-entity name="ca_project" from="ca_projectteamid" to="teamid"><filter><condition attribute="ca_projectid" operator="eq" value="' + crmForm.ObjectId + '" /></filter></link-entity></link-entity></link-entity></entity></fetch>';

    var aoFetchResults = oService.Fetch(sFetchXml); 
    var numOfRecords = aoFetchResults.length;
    if (numOfRecords > 0) return true;
  } 
  return false;
}
//==========================================================================================
// Filtered Lookup For the Project Proposer
// Bug 1600
//==========================================================================================

SetProjectProposerFilteredLookup();

function SetProjectProposerFilteredLookup()
{
//  if (crmForm.FormType == UPDATE_FORM)
//  {
    var oService = new Ascentium_CrmService();
    
    var sFilterCondotions = "";	 

    if (crmForm.all.ca_programmeid.DataValue != null && crmForm.all.ca_programmeid.DataValue[0] != null)
    {
      var sProgrammeId = crmForm.all.ca_programmeid.DataValue[0].id;

      var sFetchXmlProgrammeTeamUsers = '<fetch mapping="logical"><entity name="systemuser"><attribute name="systemuserid" /><link-entity name="teammembership" from="systemuserid" to="systemuserid"><link-entity name="team" from="teamid" to="teamid"><link-entity name="ca_programme" from="ca_teamprogrammeid" to="teamid"><filter><condition attribute="ca_programmeid" operator="eq" value="' + sProgrammeId + '" /></filter></link-entity></link-entity></link-entity></entity></fetch>';

      var aoFetchProgrammeTeamUsersResults = oService.Fetch(sFetchXmlProgrammeTeamUsers); 
      var iNumOfTeamUsers = aoFetchProgrammeTeamUsersResults.length;
      if (iNumOfTeamUsers > 0)
      {
        for (i = 0; i < iNumOfTeamUsers; i++)
        {
          sFilterCondotions += '<condition attribute="systemuserid" operator="eq" value="' + aoFetchProgrammeTeamUsersResults[0].attributes["systemuserid"].value + '" />';
        }
      }

      var sFetchXmlProgramme = '<fetch mapping="logical"><entity name="ca_programme"><attribute name="ca_budgetholderid" /><attribute name="ca_programmemanagerid" /><filter><condition attribute="ca_programmeid" operator="eq" value="' + sProgrammeId + '" /></filter></entity></fetch>';

      var aoFetchProgrammeResults = oService.Fetch(sFetchXmlProgramme); 
      var iNumOfProgs = aoFetchProgrammeResults.length;
      if (iNumOfProgs > 0)
      {
        if (typeof(aoFetchProgrammeResults[0].attributes["ca_programmemanagerid"]) != "undefined" && aoFetchProgrammeResults[0].attributes["ca_programmemanagerid"] != null) sFilterCondotions += '<condition attribute="systemuserid" operator="eq" value="' + aoFetchProgrammeResults[0].attributes["ca_programmemanagerid"].value + '" />';
        if (typeof(aoFetchProgrammeResults[0].attributes["ca_budgetholderid"]) != "undefined" && aoFetchProgrammeResults[0].attributes["ca_budgetholderid"] != null) sFilterCondotions += '<condition attribute="systemuserid" operator="eq" value="' + aoFetchProgrammeResults[0].attributes["ca_budgetholderid"].value + '" />';
      }
    }
    else
    {
      sFilterCondotions = '<condition attribute="systemuserid" operator="null" />';
    }

    var sFilteredLookupFetchXml = '<fetch mapping="logical"><entity name="systemuser"><filter type="or">' + sFilterCondotions + '</filter></entity></fetch>';
    
    crmForm.all.ca_projectmanagerid.lookupbrowse = 1;
    crmForm.all.ca_projectmanagerid.AddParam("search", sFilteredLookupFetchXml);
//  } 
}
//==========================================================================================

/* ======================================================
	Bug 2007: Project's fields "Progaramme" and "Programm Objective" should be disabled after first Grant for the project is created
*/
DisableProgrammeAndObjective = function()
{
	if (crmForm.FormType != UPDATE_FORM || !crmForm.ObjectId)
		return;
		
	var service = new Ascentium_CrmService();
	var fetchXml = '<fetch mapping="logical">\
		<entity name="ca_grant">\
		<attribute name="ca_grantid" />\
		<filter>\
			<condition attribute="ca_projectid" operator="eq" value="' + crmForm.ObjectId + '" />\
		</filter>\
		</entity>\
	</fetch>';

	var results = service.Fetch(fetchXml);
	if (results.length > 0)
	{
		// The project already has one or more grants
		(new CrmField('ca_programmeid')).Disable();
		(new CrmField('ca_programmeobjectiveid')).Disable();
	}
	else
	{
		(new CrmField('ca_programmeid')).Enable();
		(new CrmField('ca_programmeobjectiveid')).Enable();
	}
}
DisableProgrammeAndObjective();
/* End of Bug 2007 */